package com.example.onlinemallsystem.controller;

import com.example.onlinemallsystem.entity.Order;
import com.example.onlinemallsystem.service.OrderService;
import com.example.onlinemallsystem.service.UserService;
import com.example.onlinemallsystem.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/Orders")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 通过用户名创建订单
     */
    /**
     * 通过用户名创建订单
     */
    @PostMapping("/create-by-username")
    public JsonResult<Long> createOrderByUsername(@RequestBody Map<String, Object> orderData) {
        try {
            // 验证必要参数
            if (orderData.get("productId") == null) {
                return new JsonResult<>(400, "商品ID不能为空");
            }
            if (orderData.get("buyerName") == null) {
                return new JsonResult<>(400, "买家用户名不能为空");
            }
            if (orderData.get("quantity") == null) {
                return new JsonResult<>(400, "购买数量不能为空");
            }

            Long productId = Long.valueOf(orderData.get("productId").toString());
            String buyerName = orderData.get("buyerName").toString();
            Integer quantity = Integer.valueOf(orderData.get("quantity").toString());
            String sellerName = orderData.get("sellerName") != null ? orderData.get("sellerName").toString() : null;

            // 创建订单对象
            Order order = new Order();
            order.setProductId(productId);
            order.setBuyerName(buyerName);
            order.setSellerName(sellerName);
            order.setOrderStatus(0); // 待支付状态
            order.setCreateTime(new Date());

            // 如果有总金额，设置总金额
            if (orderData.get("totalAmount") != null) {
                Object totalAmountObj = orderData.get("totalAmount");
                if (totalAmountObj instanceof Number) {
                    order.setTotalAmount(BigDecimal.valueOf(((Number) totalAmountObj).doubleValue()));
                } else {
                    order.setTotalAmount(new BigDecimal(totalAmountObj.toString()));
                }
            }

            // 调用服务层创建订单
            Long orderId = Long.valueOf(orderService.createOrder(order, buyerName, productId, sellerName, quantity));
            return new JsonResult<>(200, "订单创建成功", orderId);
        } catch (NumberFormatException e) {
            return new JsonResult<>(400, "参数格式错误");
        } catch (RuntimeException e) {
            return new JsonResult<>(400, e.getMessage());
        } catch (Exception e) {
            return new JsonResult<>(500, "创建订单失败: " + e.getMessage());
        }
    }

    /**
     * 从购物车创建订单
     */
    @PostMapping("/create-from-cart")
    public JsonResult<Long> createOrderFromCart(@RequestParam Long userId) {
        try {
            Long orderId = orderService.createOrderFromCart(userId);
            return new JsonResult<>(200, "订单创建成功", orderId);
        } catch (RuntimeException e) {
            return new JsonResult<>(400, e.getMessage());
        }
    }

    /**
     * 模拟支付
     */
    @PutMapping("/{id}/pay")
    public JsonResult<Void> simulatePayment(@PathVariable Long id) {
        try {
            boolean success = orderService.simulatePayment(id);
            if (success) {
                return new JsonResult<>(200, "支付成功");
            } else {
                return new JsonResult<>(400, "支付失败");
            }
        } catch (RuntimeException e) {
            return new JsonResult<>(400, e.getMessage());
        }
    }

    /**
     * 发货
     */
    @PutMapping("/{id}/ship")
    public JsonResult<Void> shipOrder(@PathVariable Long id, @RequestParam(required = false) String trackingNumber) {
        try {
            Order order = new Order();
            order.setId(id);
            order.setOrderStatus(2); // 已发货
            order.setShipTime(new java.util.Date());

            int rows = orderService.updateOrder(order);
            if (rows > 0) {
                return new JsonResult<>(200, "发货成功");
            } else {
                return new JsonResult<>(404, "订单不存在");
            }
        } catch (Exception e) {
            return new JsonResult<>(400, "发货失败: " + e.getMessage());
        }
    }

    /**
     * 确认收货
     */
    @PutMapping("/{id}/confirm")
    public JsonResult<Void> confirmOrder(@PathVariable Long id) {
        try {
            Order order = new Order();
            order.setId(id);
            order.setOrderStatus(3); // 已完成

            int rows = orderService.updateOrder(order);
            if (rows > 0) {
                return new JsonResult<>(200, "确认收货成功");
            } else {
                return new JsonResult<>(404, "订单不存在");
            }
        } catch (Exception e) {
            return new JsonResult<>(400, "确认收货失败: " + e.getMessage());
        }
    }

    /**
     * 取消订单
     */
    @DeleteMapping("/{id}/cancel")
    public JsonResult<Void> cancelOrder(@PathVariable Long id) {
        int rows = orderService.cancelOrder(id);
        if (rows > 0) {
            return new JsonResult<>(200, "订单取消成功");
        } else {
            return new JsonResult<>(404, "订单不存在或状态不允许取消");
        }
    }

    /**
     * 修改订单信息
     */
    @PutMapping("/{id}")
    public JsonResult<Void> updateOrder(@PathVariable Long id, @RequestBody Order order) {
        order.setId(id);
        Integer currentStatus = orderService.getOrderStatus(id);
        if (currentStatus == null) {
            return new JsonResult<>(404, "订单不存在");
        }
        if (currentStatus == 4) {
            return new JsonResult<>(400, "订单已取消");
        }
        int rows = orderService.updateOrder(order);
        if (rows > 0) {
            return new JsonResult<>(200, "订单更新成功");
        } else {
            return new JsonResult<>(404, "订单不存在");
        }
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/{id}/status")
    public JsonResult<Void> updateOrderStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            Order order = new Order();
            order.setId(id);
            order.setOrderStatus(status);

            int rows = orderService.updateOrder(order);
            if (rows > 0) {
                return new JsonResult<>(200, "状态更新成功");
            } else {
                return new JsonResult<>(404, "订单不存在");
            }
        } catch (Exception e) {
            return new JsonResult<>(400, "状态更新失败: " + e.getMessage());
        }
    }

    /**
     * 查询订单详情
     */
    @GetMapping("/{id}")
    public JsonResult<Order> getOrderById(@PathVariable Long id) {
        Order order = orderService.getOrderById(id);
        if (order != null) {
            return new JsonResult<>(200, "查询成功", order);
        } else {
            return new JsonResult<>(404, "订单不存在");
        }
    }

    /**
     * 查询买家订单列表
     */
    @GetMapping("/buyer/{buyerId}")
    public JsonResult<List<Order>> getOrdersByBuyerId(@PathVariable Long buyerId) {
        List<Order> orders = orderService.getOrdersByBuyerId(buyerId);
        return new JsonResult<>(200, "查询成功", orders);
    }
    /**
     * 查询卖家订单列表
     */
    @GetMapping("/seller/{sellerId}")
    public JsonResult<List<Order>> getOrdersBySellerId(@PathVariable Long sellerId) {
        List<Order> orders = orderService.getOrdersBySellerId(sellerId);
        return new JsonResult<>(200, "查询成功", orders);
    }
    /**
     * 根据状态查询买家订单
     */
    @GetMapping("/buyer/{buyerId}/status/{status}")
    public JsonResult<List<Order>> getOrdersByStatusB(
            @PathVariable Long buyerId,
            @PathVariable Integer status) {
        List<Order> orders = orderService.getOrdersByStatusB(buyerId, status);
        return new JsonResult<>(200, "查询成功", orders);
    }
    /**
     * 根据状态查询卖家订单
     */
    @GetMapping("/seller/{sellerId}/status/{status}")
    public JsonResult<List<Order>> getOrdersByStatusS(
            @PathVariable Long sellerId,
            @PathVariable Integer status) {
        List<Order> orders = orderService.getOrdersByStatusS(sellerId, status);
        return new JsonResult<>(200, "查询成功", orders);
    }
    /**
     * 获取卖家订单列表
     */
    @GetMapping("/seller")
    public JsonResult<List<Order>> getSellerOrders(
            @RequestParam(required = false) String sellerName,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String keyword) {
        try {
            // 这里需要根据sellerName查询订单
            // 暂时返回所有订单，实际应该根据卖家名称过滤
            List<Order> orders = orderService.getAllOrders();

            // 根据状态过滤
            if (status != null) {
                orders = orders.stream()
                        .filter(order -> order.getOrderStatus().equals(status))
                        .collect(java.util.stream.Collectors.toList());
            }

            // 根据关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                String searchKeyword = keyword.toLowerCase();
                orders = orders.stream()
                        .filter(order ->
                                order.getOrderNo().toLowerCase().contains(searchKeyword) ||
                                        order.getProductName().toLowerCase().contains(searchKeyword) ||
                                        order.getBuyerName().toLowerCase().contains(searchKeyword)
                        )
                        .collect(java.util.stream.Collectors.toList());
            }

            return new JsonResult<>(200, "查询成功", orders);
        } catch (Exception e) {
            return new JsonResult<>(400, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取订单统计
     */
    @GetMapping("/stats")
    public JsonResult<Map<String, Object>> getOrderStats() {
        try {
            Map<String, Object> stats = new java.util.HashMap<>();
            // 这里可以添加订单统计逻辑
            stats.put("totalOrders", 0);
            stats.put("pendingPayment", 0);
            stats.put("pendingShipment", 0);
            stats.put("shipped", 0);
            stats.put("completed", 0);
            stats.put("cancelled", 0);

            return new JsonResult<>(200, "查询成功", stats);
        } catch (Exception e) {
            return new JsonResult<>(400, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户订单统计
     */
    @GetMapping("/stats/user/{userId}")
    public JsonResult<Map<String, Object>> getUserOrderStats(@PathVariable Long userId) {
        try {
            Map<String, Object> stats = new java.util.HashMap<>();
            // 这里可以添加用户订单统计逻辑
            stats.put("totalOrders", 0);
            stats.put("pendingPayment", 0);
            stats.put("pendingShipment", 0);
            stats.put("shipped", 0);
            stats.put("completed", 0);
            stats.put("cancelled", 0);

            return new JsonResult<>(200, "查询成功", stats);
        } catch (Exception e) {
            return new JsonResult<>(400, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取卖家订单统计
     */
    @GetMapping("/stats/seller")
    public JsonResult<List<Order>> getSellerOrders(HttpSession session) {
        try {
            // 查询该卖家的所有订单
            Long sellerId = (Long) session.getAttribute("userId");
            if (sellerId == null) {
                return new JsonResult<>(401, "未登录");
            }
            List<Order> orders = orderService.getOrdersBySellerId(sellerId);
            return new JsonResult<>(200, "查询成功", orders);
        } catch (Exception e) {
            return new JsonResult<>(400, "查询失败: " + e.getMessage());
        }
    }


}